﻿import akshare as ak
import pandas as pd
import time
import logging
from datetime import datetime, timedelta

# 设置时间参数
end_date = datetime.now().strftime("%Y%m%d")
start_date = (datetime.now() - timedelta(days=20)).strftime(
  "%Y%m%d")  # 获取20天数据确保有足够交易日

# 获取所有A股代码列表
print("开始获取所有A股代码列表")
stock_info = ak.stock_info_a_code_name()
symbol_list = stock_info["code"].tolist()
print("获取所有A股代码列表成功")

# 存储符合条件的股票
qualified_stocks = []

logging.basicConfig(
    filename='../logs/gp.log',
    level=logging.DEBUG,
    format='%(asctime)s - %(levelname)-8s - %(name)-10s - %(module)-10s - %(funcName)-10s - %(lineno)-5d - %(message)s',
    filemode='a')
file_path = "../logs/gp01.text"  #. 表示当前目录

# 遍历每只股票
for index, symbol in enumerate(symbol_list):
  try:
    time.sleep(0.2)  # 控制请求频率
    print("正在尝试股票代码:" + symbol+"获历史行情数据" + "/" + str(index+1))
    # 获取历史行情数据
    df = ak.stock_zh_a_hist(symbol=symbol, period="daily",
                            start_date=start_date, end_date=end_date, adjust="")
    print("股票代码:" + symbol+"获历史行情数据成功")
    if len(df) < 11:  # 确保有至少11个交易日的数据
      continue

    # 计算10日成交量均值（排除最后一行即当天）
    avg_volume_10 = df["成交量"].iloc[-11:-1].mean()

    # 获取当天数据（最后一行）
    today_data = df.iloc[-1]
    today_volume = today_data["成交量"]
    today_pct_change = today_data["涨跌幅"]

    # 应用筛选条件
    if (today_volume > avg_volume_10 * 2) and (abs(today_pct_change) <= 2):
      qualified_stocks.append({
        "股票代码": symbol,
        "股票名称": stock_info[stock_info["code"] == symbol]["name"].values[0],
        "当天成交量(手)": today_volume,
        "10日均量(手)": round(avg_volume_10, 2),
        "量比": round(today_volume / avg_volume_10, 2),
        "涨跌幅(%)": today_pct_change
      })
      msg = str({
        "股票代码": symbol,
        "股票名称": stock_info[stock_info["code"] == symbol]["name"].values[0],
        "当天成交量(手)": today_volume,
        "10日均量(手)": round(avg_volume_10, 2),
        "量比": round(today_volume / avg_volume_10, 2),
        "涨跌幅(%)": today_pct_change
      })
      with open(file_path, "a+", encoding='utf-8') as file:
        file.write("\n" + msg)
        while True:
          line = file.readline()
          if not line:
            break
        file.seek(0)
        while True:
          line = file.readline()
          if not line:
            break
      # 跳过无法获取数据的股票
      print(msg)
  except Exception as e:
    # 跳过无法获取数据的股票
    print("尝试股票代码:" + symbol+"获历史行情数据失败" + str(e))
    continue

# 转换为DataFrame并输出结果
if qualified_stocks:
  result_df = pd.DataFrame(qualified_stocks)
  print(f"找到 {len(result_df)} 只符合条件的股票：")
  print(result_df)

  # 保存结果到CSV
  result_df.to_csv(f"qualified_stocks_{end_date}.csv", index=False,
                   encoding="utf-8-sig")
  print(f"结果已保存到 qualified_stocks_{end_date}.csv")
else:
  print("未找到符合条件的股票")